<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/12/26
 */

namespace behavior\wechat;


use app\admin\model\wechat\WechatMessage;
use app\routine\model\store\StoreOrder as StoreOrderRoutineModel;
//use app\wap\model\store\StoreOrder as StoreOrderWapModel;
use app\common\model\Order as StoreOrderWapModel;
use app\wap\model\user\UserRecharge;
use service\HookService;
use service\RoutineRefund;
use service\WechatService;

class PaymentBehavior
{

    /**
     * 下单成功之后
     * @param $order
     * @param $prepay_id
     */
    public static function wechatPaymentPrepare($order, $prepay_id)
    {

    }

    /**
     * 微信支付成功后
     * @param $notify
     * @return bool|mixed
     */
    public static function wechatPaySuccess($notify)
    {
        file_put_contents('runtime/log/paydebug.log', json_encode([
            'date'    =>    date('Y-m-d H:i:s'),
            'type'    =>    'wechat',
            'method'  =>    'wechatPaySuccess',
            'body'    =>    file_get_contents("php://input"),
            'notify'  =>    $notify
        ]) . PHP_EOL . '---------------------------------------------------' . PHP_EOL , FILE_APPEND);

        if(isset($notify->attach) && $notify->attach){
            try {
                $fun = 'paySuccess' . ucfirst(strtolower($notify->attach));

                $res = static::$fun($notify->out_trade_no, $notify->transaction_id , $notify);

                if ( $res == true ) {
                    echo json_encode([
                        'code'    => 'SUCCESS',
                        'message' => '成功'
                    ],JSON_UNESCAPED_UNICODE);
                    return true;
                }
            } catch (\Exception $e ) {
                file_put_contents('runtime/log/paydebug.log', json_encode([
                    'date'    =>    date('Y-m-d H:i:s'),
                    'method'  =>    'wechatPaySuccess',
                    'error'   =>    $e->getMessage(),
                ]) . PHP_EOL . '---------------------------------------------------' . PHP_EOL , FILE_APPEND);
            }
            //return HookService::listen('pay_success_'.strtolower($notify->attach),$notify->out_trade_no,$notify->trade_no, $notify,true,self::class);
        }
        return false;
    }

    /**
     * 支付宝支付成功后
     * @param $notify
     * @return bool|mixed
     */
    public static function alipayPaySuccess($notify)
    {
        file_put_contents('runtime/log/paydebug.log', json_encode([
            'date'    =>    date('Y-m-d H:i:s'),
            'type'    =>    'alipay',
            'method'  =>    'alipayPaySuccess',
            'body'    =>    file_get_contents("php://input"),
            'notify'  =>    $notify
        ]) . PHP_EOL . '---------------------------------------------------' . PHP_EOL , FILE_APPEND);

        if(isset($notify->attach) && $notify->attach){
            try {
                $fun = 'paySuccess' . ucfirst(strtolower($notify->attach));

                $res = static::$fun($notify->out_trade_no, $notify->trade_no , $notify);

                if ( $res == true ) {
                    echo 'SUCCESS';
                    return true;
                }
            } catch (\Exception $e ) {
                file_put_contents('runtime/log/paydebug.log', json_encode([
                    'date'    =>    date('Y-m-d H:i:s'),
                    'method'  =>    'alipayPaySuccess',
                    'error'   =>    $e->getMessage(),
                ]) . PHP_EOL . '---------------------------------------------------' . PHP_EOL , FILE_APPEND);
            }

            //return HookService::listen('pay_success_'.strtolower($notify->attach),$notify->out_trade_no,$notify->trade_no,$notify,true,self::class);
        }
        return false;
    }

    /**
     * 预购订单
     * 支付成功
     * @Author   FW
     * @DateTime 2021-05-24
     * @Email    123763712@qq.com
     * @param    [type]           $orderId [description]
     * @param    [type]           $out_trade_no  [description]
     * @return   [type]                    [description]
     */
    public static function paySuccessPrecharse($order_no, $out_trade_no , $notify)
    {
        try{
            $order = StoreOrderWapModel::where('order_no' , $order_no)->find();

            if( empty($order) ) {
                file_put_contents('runtime/log/paydebug.log', json_encode([
                    'date'     =>    date('Y-m-d H:i:s'),
                    'method'   =>    'paySuccessEnroll',
                    'msg'      =>    'order is empty',
                    'order_no' =>    $order_no,
                    'out_trade_no' => $notify->out_trade_no
                ]) . PHP_EOL . '---------------------------------------------------' . PHP_EOL , FILE_APPEND);
            }
            if ( $order->pay_status == 1 ) return true;

            return StoreOrderWapModel::paySuccess($order_no , $out_trade_no , $order->pay_type );
        }catch (\Exception $e){

            file_put_contents('runtime/log/paydebug.log', json_encode([
                'date'    =>    date('Y-m-d H:i:s'),
                'method'  =>    'wechatPaySuccessEnrollException',
                'exception'    =>   $e->getMessage(),
            ]) . PHP_EOL . '---------------------------------------------------' . PHP_EOL , FILE_APPEND);

            return false;
        }
    }

    /**
     * 用户成为合伙人
     * @param $orderId
     * @param $notify
     * @return bool
     */
    public static function wechatPaySuccessUserPartner($orderId, $notify)
    {
        try{
            if(UserRecharge::be(['order_id'=>$orderId,'paid'=>1])) return true;
            return UserRecharge::UserPartnerSuccess($orderId);
        }catch (\Exception $e){
            return false;
        }
    }
    public static function wechatPaySuccessBuyVip($orderId, $notify){
        try{
            if(UserRecharge::be(['order_id'=>$orderId,'paid'=>1])) return true;
            return UserRecharge::paySuccessBuyVip($orderId);
        }catch (\Exception $e){
            return false;
        }
    }

    /**
     * 微信支付订单退款
     * @param $orderNo
     * @param array $opt
     */
    public static function wechatPayOrderRefund($orderNo, array $opt)
    {
        WechatService::payOrderRefund($orderNo,$opt);
    }

    public static function routinePayOrderRefund($orderNo, array $opt)
    {
        $refundDesc = isset($opt['desc']) ? $opt['desc'] : '';
        $res = RoutineRefund::doRefund($opt['pay_price'],$opt['refund_price'],$orderNo,'',$orderNo,$refundDesc);
    }

    /**
     * 微信支付充值退款
     * @param $orderNo
     * @param array $opt
     */

    public static function userRechargeRefund($orderNo, array $opt)
    {
        WechatService::payOrderRefund($orderNo,$opt);
    }
}